package com.elephant.core.socket.socket2;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author hai
 * @description
 * @date 11:36 2018/8/31
 */
public class ServerV {

    public static void main(String[] args) throws IOException {

        int port = 8888;
        ServerSocket server = new ServerSocket(port);
        Socket accept = server.accept();
        Reader reader = new InputStreamReader(accept.getInputStream());

        char[] chars = new char[64];
        int len;
        StringBuilder sb = new StringBuilder();
        String temp;
        int index;
        while ((len = reader.read(chars)) != -1){
            temp = new String(chars, 0, len);

            //遇到eof结束接收
            if((index = temp.indexOf("eof")) != -1){
                sb.append(temp, 0, index);
                break;
            }
            sb.append(temp);
        }

        System.out.println("From Client:" + sb);

        Writer writer = new OutputStreamWriter(accept.getOutputStream());
        writer.write("Hello Client");
        writer.flush();
        writer.close();

        reader.close();
        accept.close();
        server.close();
    }
}
